package com.xx.sg.config;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.IOException;

public class NullIfEmptyStringObjectDeserializer extends JsonDeserializer<ObjectNode> {
    @Override
    public ObjectNode deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {
        // 解析原始对象
        ObjectNode node = jsonParser.getCodec().readTree(jsonParser);

        // 遍历字段，如果值为空字符串，则设置为 null
        node.fields().forEachRemaining(entry -> {
            if (entry.getValue().isTextual() && entry.getValue().asText().trim().isEmpty() && entry.getValue().asText().equals("null")) {
                node.set(entry.getKey(), null);  // 空字符串转换为 null
            }
        });

        return node;
    }
}
